package com.xoa.service.secureKey;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.secureKey.SecureKeyMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.secureKey.SecureKey;
import com.xoa.model.users.Users;
import com.xoa.util.ToJson;
import com.xoa.util.page.PageParams;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import seamoonotp.seamoonapi;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;
import java.util.UUID;

/**
 * Created by zhanglijun on 2019/7/26.
 */
@Service
public class SecureKeyService {

    @Resource
    private SecureKeyMapper secureKeyMapper;

    @Resource
    private UsersMapper usersMapper ;

    @Resource
    private DepartmentMapper departmentMapper;


    public ToJson<SecureKey> ImportSecureKeyInfo(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<SecureKey> json = new ToJson<SecureKey>(1,"error");

            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            StringBuffer buffer=new StringBuffer();
            if(osName.toLowerCase().startsWith("win")){
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if(uploadPath.indexOf(":")==-1){
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if(basePath.indexOf("/xoa")!=-1){
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2=basePath.substring(0,index);
                    }
                    path = path.append(str2 + "/xoa");
                }
                path.append(uploadPath);
                buffer=buffer.append(rb.getString("upload.win"));
            }else{
                path=path.append(rb.getString("upload.linux"));
                buffer=buffer.append(rb.getString("upload.linux"));
            }
            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".smd")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);



                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();

                    SecureKey secureKey = new SecureKey();
                    // 读入TXT文件
                    // 绝对路径或相对路径都可以，这里是绝对路径，写入文件时演示相对路径
                    String pathname = readPath;
                    // 要读取以上路径的input。txt文件
                    File filename = new File(pathname);
                    try (InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); BufferedReader br = new BufferedReader(reader)){
                        file.transferTo(dest);
                    String line;
                    // 一次读入一行数据
                    while ((line = br.readLine() )!= null) {
                       String[] strings = line.split(",");
                       secureKey.setKeySn(strings[0]);
                       secureKey.setKeyInfo(strings[1]);
                       SecureKey secureKey1 = secureKeyMapper.selectByPrimaryKey(strings[0]);
                       if(secureKey1!=null){
                           secureKeyMapper.updateByPrimaryKeySelective(secureKey);
                       }else {
                           secureKeyMapper.insertSelective(secureKey);
                       }
                    }
                    } catch (Exception e) {
                        e.printStackTrace();
                        json.setMsg("数据保存异常");
                        json.setFlag(1);
                    }
                }
            }
            json.setFlag(0);
            json.setMsg("ok");

        return json;
    }

    public ToJson<SecureKey> SelectSecureKeyInfo(HttpServletRequest request, Integer page, Integer pageSize, boolean useFlag) {
        ToJson<SecureKey> json = new ToJson<SecureKey>(1,"error");
        try{
            //分页
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            HashMap<String,Object> map = new HashMap();
            map.put("pageParams", pageParams);
            List<SecureKey> list = secureKeyMapper.selectSecureKeyInfo(map);
            if(list!=null&&list.size()>0){
                for(SecureKey secureKey : list){
                    Users users = usersMapper.selectUserNameByKey(secureKey.getKeySn());
                    if(users!=null){
                        secureKey.setUserName(users.getUserName());
                        secureKey.setUid(users.getUid());
                        if(users.getDeptId()!=null){
                            secureKey.setDeptName(departmentMapper.selectById(users.getDeptId()));
                        }
                    }
                }
                json.setMsg("ok");
                json.setObj(list);
                json.setTotleNum(pageParams.getTotal());
                json.setFlag(0);
            }

        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("数据异常");
            json.setFlag(1);
        }
        return json;
    }

    public ToJson<SecureKey> deleteSecureKeyInfo(HttpServletRequest request, String keySn) {
        ToJson<SecureKey> json = new ToJson<SecureKey>(1,"error");
        try{
            if(keySn!=null&& !keySn.equals("")){
                int a = secureKeyMapper.deleteByPrimaryKey(keySn);
                if(a>0){
                    json.setFlag(0);
                    json.setMsg("删除成功");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("数据异常");
            json.setFlag(1);
        }
        return json;
    }

    public ToJson<SecureKey> passwordsyn(HttpServletRequest request, String keySn, String dynPassword) {
        ToJson<SecureKey> json = new ToJson<SecureKey>(1,"ok");
        try{
            //声明包类对象
            seamoonapi sc=new seamoonapi();
            String sninfo="",str="";
           // String sn="795100000";
            //从你的数据库中把sn的加密字符串取出来
            SecureKey secureKey = secureKeyMapper.selectByPrimaryKey(keySn);
            sninfo = secureKey.getKeyInfo();

            //同步密码接口 ，提供给管理员使用的功能
            str=sc.passwordsyn(sninfo,dynPassword);
            if (str.length()>3)
            {
                //System.out.println("同步动态密码成功");
                // 把更新后的字符串更新到你的数据库中（只有同步成功后才需要更新字符串）
                SecureKey secureKey1 = new SecureKey();
                secureKey1.setKeySn(keySn);
                secureKey1.setKeyInfo(str);
                secureKeyMapper.updateByPrimaryKeySelective(secureKey1);
                json.setMsg("同步密码卡成功");
            }
            else if(str.equals("-1"))
            {
                //System.out.println("SN字符串有错");
            }
            else if(str.equals("0"))
            {
                //System.out.println("同步动态密码错误");
            }
            else
            {
               // System.out.println("未知错误");
            }

        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("数据异常");
            json.setFlag(1);
        }
        return json;
    }
}
